#include "usermanager.h"

bool UserManager::login(std::string name,std::string password)
{
    for(int i = 0;i < users.size();i++)
    {
        if(users[i].username == name)
        {
            if(users[i].CheckPassword(password))
            {
                logined = 1;
                loginedUser = &users[i];
                return 1;
            }
        }
    }
    return 0;
}

bool UserManager::logout()
{
    if(!logined)
        return 0;
    loginedUser = nullptr;
    logined = 0;
    return 1;
}

bool UserManager::adduser(user _user)
{
    for(user middle : users)
    {
        if(middle.username == _user.username)
            return 0;
    }
    users.emplace_back(_user);
    return 1;
}

void UserManager::loadDataFromLocalDataBase(std::string path)
{
    std::fstream database(path);
    if(!database.is_open())
        return;
    int datasum;
    database >> datasum;
    for(int i = 0;i<datasum;i++)
    {
        std::string username;
        std::string password;
        database >> username;
        database >> password;
        user data(username,password);
        data.isadmin = false;
        users.emplace_back(data);
    }
}